﻿using System;
using System.IO;
using System.Text;
using System.Web;

namespace Common
{
    public class Util
    {
        public static string GetHost()
        {
            return "http://"+HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
        }

        /// <summary>
        /// 时间戳转为C#格式时间
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <returns></returns>
        public static DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

        #region 写文件
        public static bool CreatFile(string savePath, string fileStr)
        {
            if (!savePath.Contains(":"))
            {
                savePath = AppDomain.CurrentDomain.BaseDirectory + savePath;
            }
            StreamWriter sw = new StreamWriter(savePath, false, Encoding.UTF8);
            try
            {
                sw.Write(fileStr);
                sw.Flush();
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                sw.Close();
                sw.Dispose();
            }
        }
        #endregion

        #region 删除文件
        public static void DelFile(string filePath)
        {
            if (File.Exists(filePath))
                File.Delete(filePath);
        }
        #endregion

        #region 文件附加内容
        public static bool AppendFile(string savePath, string fileStr)
        {
            if (!savePath.Contains(":"))
            {
                savePath = AppDomain.CurrentDomain.BaseDirectory + savePath;
            }
            var sw = new StreamWriter(savePath, true, Encoding.UTF8);
            try
            {
                sw.WriteLine(fileStr);
                sw.Flush();
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                sw.Close();
                sw.Dispose();
            }
        }
        #endregion

        #region 错误记录
        public static void Log(string fileStr)
        {
            string logFilePath = AppDomain.CurrentDomain.BaseDirectory + "/log/" + DateTime.Now.ToString("yyMMdd") + ".txt";
            if (!File.Exists(logFilePath))
            {
                CreatFile(logFilePath, fileStr);
                return;
            }
            AppendFile(logFilePath, DateTime.Now + ":" + fileStr);
        }
        #endregion
    }
}
